import React,{Component,Fragment} from 'react';
import Layout from './Layout';
import layoutMC from './static/css/layout.module.css';
import userMC from './static/css/user.module.css';
import messageMC from './static/css/message.module.css';
import User from './component/User';
import SiderBar from './component/SiderBar';
import GroupBlock from './component/GroupBlock'
import SendMessage from './component/SendMessage';
import ShowMessage from './component/ShowMessage';
import WSocket from './utils/wSocket';
import { Message } from 'antd';
import store from './store';

class Chat extends Component{
  constructor(props){
    super(props);
    this.state = {
      userName:'',
      tmpName:'',
      confirmLoading:false,
      visiable:false,
      createName:false,
      disabled:true,
      group:[],
      messageList:[]
    }
    this.socket = null;
    this.sendList = {};
    this.sendNum = 0;
  }
  render(){
    return(
      <Fragment>
        <Layout>
          <div header="true">
            <span className={layoutMC.title}>小黑屋聊天室</span>
            <div className={userMC.user}>
              <User 
              addUser={this.addUser.bind(this)} 
              joinUsBtn={this.joinUsBtn.bind(this)}  
              handleCancel={this.handleCancel.bind(this)}
              userName={this.state.userName} confirmLoading={this.state.confirmLoading} visiable={this.state.visiable} />
            </div>
          </div>
          <div className={layoutMC.siderBox} sider="true">
            <div className={layoutMC.siderBar}>
              <SiderBar />
            </div>
            <div className={layoutMC.groupBlock}>
              <GroupBlock group={this.state.group} />
            </div>
          </div>
          <div className={layoutMC.chatBox} content="true">
            <div className={messageMC.messageBox}>
              <p>群聊</p>
              <div ref="messageBoxContent" className={messageMC.messageBoxContent}>
                <ShowMessage message={this.state.messageList} changeScroll={this.changeScroll.bind(this)} />
              </div>
            </div>
            <div className={messageMC.inputBox}>
              <SendMessage sendSure={this.sendSure.bind(this)} disabled={this.state.disabled}/>
            </div>
          </div>
        </Layout>
      </Fragment>
    )
  }
  sendSure(msg){
    this.sendNum += 1;
    let sendMsg = {"type":"message","text":msg,'id':this.sendNum}
    this.socket.sendMessage(sendMsg);
    
    //暂时在面板显示
    let one = {};
    one['states'] = 'loading';
    one['type'] = 'message';
    one['oriention'] = 'self';
    one['text'] = msg;
    one['title'] = '';
    this.setState({
      messageList:[...this.state.messageList,one]
    });
    let sendTime = setTimeout(()=>{
      let messageList = this.state.messageList;
      let mIndex = messageList.indexOf(one);
      messageList.splice(mIndex,1);
      one['states'] = 'close';
      messageList.push(one);
      this.setState({
        messageList:messageList
      });
    },3000);
    //储存发送队列
    let sendInfo = {'time':sendTime,'info':one};
    this.sendList[this.sendNum] = sendInfo;
  }
  joinUsBtn(){
    this.setState({
      visiable:true
    });
  }
  handleCancel(){
    this.setState({
      visiable:false
    });
  }
  addUser(name){
    this.setState({
      confirmLoading:true,
      tmpName:name
    });
    let sendMsg = {"type":"name","text":name}
    this.socket.sendMessage(sendMsg);

    
  }
  //链接socket
  componentDidMount(){
    const webUrl = 'ws://103.75.46.244/ws';
    this.socket = new WSocket({
      socketUrl:webUrl,
      timeout:10000,
      name:'bob',
      socketOpen:()=>{
        Message.info('连接成功');
        //判断session中是否有username
        if(sessionStorage.getItem('name')){
          let name = sessionStorage.getItem('name');
          this.addUser(name);
        }
      },
      socketMessage:(msg) => {
        let data = JSON.parse(msg['data']);
        if(data['type'] === 'self'){
          if(data['code'] == 200){
            this.setState({
              confirmLoading:false,
              visiable:false,
              userName:this.state.tmpName,
              disabled:false
            });
            //储存username
            sessionStorage.setItem('name',this.state.tmpName);
          }
        }
        else if(data['type'] === 'alter'){
          if(data['code'] == 300){
            Message.info(data['text']);
            this.setState({
              confirmLoading:false,
            });
          }
        }
        else if(data['type'] === 'tip'){
          if(data['code'] == 200){
            let one = {};
            one['states'] = 'check';
            one['type'] = 'tip';
            one['oriention'] = 'other';
            one['text'] = data['text'];
            one['title'] = '';
            this.setState({
              messageList:[...this.state.messageList,one]
            });
          }
        }
        else if(data['type'] == 'group'){
          if(data['code'] == 200){
            let newGroup = data['text'];
            this.setState({
              group:newGroup
            });
          }
        }
        else if(data['type'] == 'message'){
          if(data['code'] == 200){
            let one = {};
            one['state'] = 'check';
            one['type'] = 'message';
            one['oriention'] = 'other';
            one['text'] = data['text'];
            one['title'] = data['title'];
            this.setState({
              messageList:[...this.state.messageList,one]
            });
          }
        }
        else if(data['type'] == 'selfM'){
          if(data['code'] == 200){
            let id = data['id'];
            let sendTime = this.sendList[id]['time'];
            clearTimeout(sendTime);
            let info = this.sendList[id]['info'];
            let messageList = this.state.messageList;
            let index = messageList.indexOf(info);
            info['states'] = 'check';
            messageList.splice(index,info);
            this.setState({
              messageList:messageList
            });
          }
        }
      },
      socketClose:(e) => {
        Message.info('连接断开');
      },
      socketError:(e) => {
        Message.info('连接错误');
      }
    });
    try{
      this.socket.connection().then((data)=>{

      }).catch((e)=>{
        Message.info(e);
      });
    }
    catch(e){
      console.log(e);
    }
  }
  //滚动条发送信息时滚到最后
  changeScroll(ulHeight){
    let boxHeight = this.refs.messageBoxContent.clientHeight;
    if(ulHeight > boxHeight){
      let sHeight = ulHeight - boxHeight;
      this.refs.messageBoxContent.scrollTop = sHeight;
    }
    else{
      return false;
    }
  }
}

export default Chat;